<template>
  <div class="shopping-cart fixed-header fixed-footer">
    <x-header>方案内容</x-header>
    <div class="top-actions">
      <div class="action">
        <router-link to="/jingcai" tag="b"><i class="iconfont icon-plus"></i> 添加/编辑方案</router-link>
      </div>
      <div class="text-grey tips py-1">已选<b>{{Object.keys(bet).length}}</b>场{{matches.length ? `, 截止时间 ${matches[0].endTime}` : ''}}</div>
    </div>

    <transition-group class="mx-3 relative" name="cart" tag="div">
      <div class="cart-item text-center" @click="popup(m.matchId)" :key="m.matchId" v-for="m in matches">
        <template v-if="['rqspf', 'spf'].includes(rule)">
          <div class="d-flex py-2 pr-3">
            <i class="iconfont icon-close-o align-self-end" @click.stop="del(m.matchId)"></i>
            <cart-spf :m="m" :rule="rule" v-model="bet[m.matchId]"/>
          </div>
        </template>
        <template v-else>
          <div class="desc">{{m.hostShort}}<i class="text-grey mx-5">VS</i>{{m.guestShort}}</div>
          <div class="bet">
            <i class="iconfont icon-close-o" @click.stop="del(m.matchId)"></i>
            <em class="text-red" v-html="stringify(m.matchId)"></em>
          </div>
        </template>
      </div>
    </transition-group>

    <div class="text-grey m-3" style="padding-left: 3.5rem" v-if="Object.keys(passing).length">
      <label class="ui-check"><input type="checkbox" v-model="agree"><i></i> 我已阅读并同意</label>
      <a @click.prevent="toggle('dialog')" href>《服务协议》</a>
      <a class="float-right" @click="empty">清空列表</a>
    </div>
    <div class="text-center text-grey mt-2" v-else><i class="iconfont icon-info align-middle"></i> 请至少选择2场比赛</div>

    <popup v-model="dialog" class="dialog-lg dialog-flex" style="height: 75%">
      <div class="scroll-wrapper flex-column grow">
        <iframe class="grow" src="http://r209.chaoshenwan.com/lottery/public/faq/agreement.html"></iframe>
      </div>
      <a class="btn btn-lg btn-danger rad-0" @click="toggle('dialog')">确定</a>
    </popup>

    <popup v-if="m" v-model="show" class="dialog-lg">
      <component v-if="popup()" :is="'popup-' + rule" :m="m" v-model="bet[m.matchId]" @hide="toggle('show')"/>
    </popup>

    <masker v-model="type"/>

    <checkout :disabled="!agree || !bets.bets" :bets="bets.bets" v-model="times" @checkout="checkout">
      <div class="text-center clickable text-truncate w-50 br-l" @click="toggle('type')" slot="left" v-if="Object.keys(passing).length">
        <i v-if="type">收起</i>
        <i v-else v-html="passes.length ? passes.map(p => passing[p]).join(', ') : '过关方式<b>(必选)</b>'"></i>
        <i class="iconfont font-sm" :class="type ? 'icon-arrow-down' : 'icon-arrow-up'"></i>
      </div>
      <div class="text-center clickable w-50 br-l" slot="left" v-else>请至少选择<b class="text-red">2</b>场比赛</div>
      <div slot="extra" class="bg-grey">
        <div class="d-flex wrap px-2 pb-3 bt-l" v-if="type">
          <div class="rule box-lg" :class="{on: passes.includes(k)}" @click="select(k)" v-for="(v, k) in passing">
            <a class="mx-3 mt-3 b-l">{{v}}</a>
          </div>
        </div>
        <!--<div class="text-right">2串1，3串1等是什么意思 ></div>-->
      </div>
      <small class="text-grey" slot="tips">预计奖金{{bets.bonus}}</small>
    </checkout>
  </div>
</template>

<script>
import { Popup } from 'vant'
import http, { checkout } from '../../http'
import { betContent, fixed, isBetOne, minmaxOdds } from './calculator'
import { combination, compare, select } from '../../utils/arrays'
import { get, remove, set } from '../../utils/stoage'
import Checkout from '../widgets/checkout'
import PopupHhgg from './popup-hhgg'
import PopupBqc from './popup-bqc'
import PopupZjq from './popup-zjq'
import PopupBf from './popup-bf'
import CartSpf from './cart-spf'
import Masker from '../widgets/masker'

const map = {}

export default {
  components: {CartSpf, PopupHhgg, PopupBqc, PopupZjq, PopupBf, Popup, Checkout, Masker},
  name: 'jingcai-cart',
  data: () => ({
    dialog: false,
    passes: [],
    agree: true,
    times: 10,
    show: false,
    type: false,
    rule: '',
    bet: {},
    m: null
  }),
  beforeRouteEnter (to, from, next) {
    http.post('/jingcai/matches').then(res => {
      next(vm => {
        var rule = get('jingcai.rule', {rule: 0}).rule
        if (!rule) {
          next('/jingcai')
        }
        var bet = get('jingcai.bet.' + rule, {})
        res.betList.map(b => {
          b.matchList.forEach(m => {
            if (m.matchId in bet) {
              map[m.matchId] = m
            }
          })
        })
        Object.keys(bet).forEach(k => {
          if (!(k in map)) {
            delete bet[k]
          }
        })
        vm.passes = get(`jingcai.passes.${rule}`, [])
        vm.rule = rule
        vm.bet = bet
      })
    })
  },
  beforeDestroy () {
    if (this.rule) {
      set(`jingcai.bet.${this.rule}`, this.bet)
      if (this.passes.length) {
        set(`jingcai.passes.${this.rule}`, this.passes)
      }
    }
  },
  methods: {
    checkout (times) {
      var {bet, rule, passes} = this
      checkout.call(this, '/jingcai/bet', 'jingcai', {
        betContent: betContent(bet, rule),
        passType: passes.map(p => '10' + p).join(','),
        times,
        rule
      }, function () {
        remove(`jingcai.bet.${rule}`)
      })
    },
    stringify (key) {
      return this.bet[key].map(v => {
        var [rule, bet] = v.split('|')
        if (rule == 'zjq') {
          if (bet == 7) {
            bet += '+'
          }
          bet += '球'
        }
        return bet
      }).join(' ')
    },
    toggle (prop) { this[prop] = !this[prop] },
    popup (key) {
      switch (this.rule) {
        case 'hhgg':
        case 'bqc':
        case 'zjq':
        case 'bf':
          if (key) {
            this.m = map[key]
            this.$nextTick(() => this.show = true)
          }
          return this.rule
      }
    },
    empty () {
      this.$dialog.alert({
        title: '清空',
        showCancelButton: true,
        message: '是否清空所选内容？',
        onConfirm: () => {
          this.bet = set(`jingcai.bet.${this.rule}`, {})
        }
      })
    },
    select (n) {
      this.passes = select(this.passes, n).sort()
    },
    del (key) {
      this.$delete(this.bet, key)
      var keys = Object.keys(this.bet)
      this.passes = this.passes.filter(p => p <= keys.length)
      set(`jingcai.bet.${this.rule}`, this.bet)
    }
  },
  computed: {
    passing () {
      var keys = Object.keys(this.bet)
      var obj = {}
      if (keys.length == 1) {
        if (isBetOne(map[keys[0]], this.rule)) {
          obj[1] = '单关'
        }
      } else {
        for (let i = 1; i < Math.min(keys.length, 8); i++) {
          obj[i + 1] = i + 1 + '串1'
        }
      }
      return obj
    },
    matches () {
      return Object.keys(this.bet).map(k => map[k]).sort((a, b) => {
        var l = a.endTime.replace(/[^\d]/g, '')
        var r = b.endTime.replace(/[^\d]/g, '')
        return l - r + a.matchNo - b.matchNo
      })
    },
    bets () {
      var {bet, times, passes} = this
      var keys = Object.keys(bet).filter(k => bet[k].length)

      var odds = minmaxOdds(map, bet)

      var min = 0, max = 0
      if (passes.length && keys.length >= passes[0]) {
        min = keys.map(k => odds[k][0])
          .sort(compare)
          .slice(0, passes[0])
          .reduce((v, e) => {
            v *= parseFloat(e)
            return v
          }, 1)
        min = (fixed(min * 2) * times).toFixed(2)
      }

      // 计算总注数
      var bets = passes.reduce(function (sum, n) {
        combination(keys, n, function (arr) {
          var val = 1
          sum += arr.reduce(function (r, key) {
            val *= parseFloat(odds[key][1])
            return r * bet[key].length
          }, 1)
          max += val
        })
        return sum
      }, 0)

      max = (fixed(max * 2) * times).toFixed(2)

      return {
        bonus: min == max ? `${min}元` : `${min}~${max}元`,
        bets
      }
    }
  }
}
</script>
